<?php if (!defined('BASEPATH'))exit('No direct script access allowed');

class Wenda extends MY_Controller {

    function __construct() {
        parent::__construct();
    }

    function index($type,$value) {
        if($type == "tag"){
            $tag_info = $this->db->select("name")->from("bbs_wenda_tags")->where(array('id'=>$value))->order_by("id desc")->get()->row_array();
            if(!$tag_info){//不存在标签
                $this->assign("error", "标签不存在或已被系统管理员删除");
                $this->display('deleted/index.html');exit;
            }
            $tag_name = $tag_info['name'];
        }
        
        $this->right();
        $this->assign("type", $type ? $type : 0);
        $this->assign("value", $value ? $value : 0);
        $this->assign("tag_name", $tag_name ? $tag_name : 0);
        $this->display('wenda/index.html');
    }
    
    function search(){
        
        if(!isset($_GET['kw'])){
            web_redirect("/forum.php/wenda.html");
        }
        $keyword = isset($_GET['kw']) ? trim($_GET['kw']) : "";
        
        $this->right();
        $this->assign("keyword", $keyword);
        $this->display('wenda/seach.html');
    }
    function detail($wenda_id,$answer_id,$reply_id) {
        $wenda_id = $wenda_id ? decrypt_wenda_id($wenda_id) : 0;
        $wenda = $this->db->select("w.*,u1.nickname q_user_nickname,u1.head_img q_user_headimg")
                ->from("bbs_wenda w")->join("users_info u1","u1.user_id = w.questioner_id","left")->where(array("w.id"=>$wenda_id,"w.status"=>1,"w.is_show"=>1))->order_by("w.id desc")->get()->row_array();
        if(!$wenda){
            $this->assign("error", "您查找的问答不存在或已被删除");
            $this->display('deleted/index.html');exit;
        }
        
        $tags = array();
        if($wenda['tags_name']){
            $tags_arr = explode(",", $wenda['tags_name']);
            foreach ($tags_arr as $v){
                $v = explode("_", $v);
                $tags[$v[1]] = array("tid"=>$v[1],"tname"=>$v[0],"turl"=>  web_url("wenda/tag-".$v[1])); 
            }
        }
        $wenda['tags'] = $tags;
        $wenda['wenda_id'] = encrypt_wenda_id($wenda_id);
        $wenda['wenda_uid'] = encrypt_user_id($wenda['questioner_id']);
        $wenda['share_url'] = share_url("wenda/".$wenda['wenda_id']);
        $wenda['is_care'] = $this->bbs_userinfo['user_id'] ?($this->db->select("*")->from("bbs_wenda_care")->where(array("user_id"=>$this->bbs_userinfo['user_id'],"wenda_id"=>$wenda_id,"is_del"=>1))->order_by("id")->get()->num_rows() ? 1 : 0) : 0;
        if($reply_id){
            $reply_id = decrypt_answer_reply_id($reply_id);
            //查找目标评论
            $reply = $this->db->select("answer_id")->from("bbs_wenda_reply")->where(array("wenda_id"=>$wenda_id,"id"=>$reply_id,"is_show"=>1))->order_by("id desc")->get()->row_array();
            if($reply){
                //查找目标答案
                $top_answer = $this->db->select("a.*,u.head_img,u.nickname")->from("bbs_wenda_answer a")->join("users_info u","u.user_id=a.user_id","left")->where(array("a.wenda_id"=>$wenda_id,"a.id"=>$reply['answer_id'],"a.is_show"=>1))->order_by("a.id desc")->get()->row_array();
                if($top_answer){
                    $top_answer['create_time'] = $this->set_time($top_answer['create_time']);
                    $top_answer['answer_id'] = encrypt_answer_id($top_answer['id']);
                    //计算该评论所处第几页
                    $pre_count = $this->db->select("*")->from("bbs_wenda_reply")->where(array("wenda_id"=>$wenda_id,"answer_id"=>$top_answer['id'],"id <="=>$reply_id,"is_show"=>1))->order_by("id asc")->get()->num_rows();
                    $per_page_num = 12;
                    $current_page = ceil($pre_count/$per_page_num) - 1;
                    //获取评论前2条记录
                    $answer_replys_list = array();
                    $top_answer['reply'] = $answer_replys_list;
                    $top_answer['reply_count'] = $top_answer['commentnum'];
                    $top_answer['current_page'] = $current_page;
                    $top_answer['user_id'] = encrypt_user_id($top_answer['user_id']);
                    $top_answer['is_answer_goto'] = 0;
                    $top_answer['is_reply_goto'] = 1;
                    $top_answer['is_self'] = $top_answer['user_id'] == $this->bbs_userinfo['user_id'];
                    $top_answer['is_page'] = 1;
                    $top_answer['share_url'] = share_url("wenda/".encrypt_wenda_id($top_answer['wenda_id'])."/answer-".  encrypt_answer_id($top_answer['id']));
                    $top_answer['target_id'] = encrypt_answer_reply_id($reply_id);
                    $top_answer['answer_url'] = web_url("wenda/".encrypt_wenda_id($top_answer['wenda_id'])."/answer-".  encrypt_answer_id($top_answer['id']));
                    $top_answer['is_like'] = $this->bbs_userinfo['user_id'] ?($this->db->select("*")->from("bbs_wenda_answer_like")->where(array("user_id"=>$this->bbs_userinfo['user_id'],"answer_id"=>$top_answer['id'],"is_del"=>1))->order_by("id")->get()->num_rows() ? 1 : 0) : 0;
                }
            }else{
                $this->assign("error", "您查找的答案评论不存在或已被删除");
                $this->display('deleted/index.html');exit;
            }
        }elseif($answer_id){
            $answer_id = decrypt_answer_id($answer_id);
            $top_answer = $this->db->select("a.*,u.head_img,u.nickname")->from("bbs_wenda_answer a")->join("users_info u","u.user_id=a.user_id","left")->where(array("a.wenda_id"=>$wenda_id,"a.id"=>$answer_id,"a.is_show"=>1))->order_by("a.id desc")->get()->row_array();
            if($top_answer){
                $top_answer['create_time'] = $this->set_time($top_answer['create_time']);
                $top_answer['answer_id'] = encrypt_answer_id($top_answer['id']);
                //获取评论前2条记录
                $answer_replys_list = $this->db->select("r.*,u1.head_img,u1.nickname nickname1,u2.nickname nickname2")->from("bbs_wenda_reply r")->join("users_info u1","u1.user_id=r.user_id","left")->join("users_info u2","u2.user_id=r.reply_uid","left")->where(array("answer_id"=>$top_answer['id'],"is_show"=>1))->order_by("id asc")->limit(2)->get()->result_array();
                foreach ($answer_replys_list as $key=>$reply){
                    $answer_replys_list[$key]['space_url1'] = web_url("u/".encrypt_user_id($reply['user_id']));
                    $answer_replys_list[$key]['space_url2'] = $reply['reply_id'] ? web_url("u/".encrypt_user_id($reply['reply_uid'])) : "";
                    $answer_replys_list[$key]['create_time'] = $this->set_time_two($reply['create_time']);
                    $answer_replys_list[$key]['answer_reply_id'] = encrypt_answer_reply_id($reply['id']);
                    $answer_replys_list[$key]['reply_url'] = web_url("wenda/".encrypt_wenda_id($reply['wenda_id'])."/answer/".  encrypt_answer_id($reply['answer_id'])."/reply-".encrypt_answer_reply_id($reply['id']));
                }
                $top_answer['reply'] = $answer_replys_list;
                $top_answer['reply_count'] = $top_answer['commentnum'];
                $top_answer['is_self'] = $top_answer['user_id'] == $this->bbs_userinfo['user_id'];
                $top_answer['user_id'] = encrypt_user_id($top_answer['user_id']);
                $top_answer['current_page'] = 0;
                $top_answer['is_answer_goto'] = 1;
                $top_answer['is_reply_goto'] = 0;
                $top_answer['is_page'] = 0;
                $top_answer['target_id'] = encrypt_answer_id($answer_id);
                $top_answer['share_url'] = share_url("wenda/".encrypt_wenda_id($top_answer['wenda_id'])."/answer-".  encrypt_answer_id($top_answer['id']));
                $top_answer['answer_url'] = web_url("wenda/".encrypt_wenda_id($top_answer['wenda_id'])."/answer-".  encrypt_answer_id($top_answer['id']));
                $top_answer['is_like'] = $this->bbs_userinfo['user_id'] ?($this->db->select("*")->from("bbs_wenda_answer_like")->where(array("user_id"=>$this->bbs_userinfo['user_id'],"answer_id"=>$top_answer['id'],"is_del"=>1))->order_by("id")->get()->num_rows() ? 1 : 0) : 0;
            }else{
                $this->assign("error", "您查找的问答答案不存在或已被删除");
                $this->display('deleted/index.html');exit;
            } 
            
        }elseif($this->bbs_userinfo['user_id']){
            $top_answer = $this->db->select("a.*,u.head_img,u.nickname")->from("bbs_wenda_answer a")->join("users_info u","u.user_id=a.user_id","left")->where(array("a.wenda_id"=>$wenda_id,"a.user_id"=>$this->bbs_userinfo['user_id'],"a.is_show"=>1))->order_by("a.id desc")->get()->row_array();
            if($top_answer){
                $top_answer['create_time'] = $this->set_time($top_answer['create_time']);
                $top_answer['answer_id'] = encrypt_answer_id($top_answer['id']);
                //获取评论前2条记录
                $answer_replys_list = $this->db->select("r.*,u1.head_img,u1.nickname nickname1,u2.nickname nickname2")->from("bbs_wenda_reply r")->join("users_info u1","u1.user_id=r.user_id","left")->join("users_info u2","u2.user_id=r.reply_uid","left")->where(array("answer_id"=>$top_answer['id'],"is_show"=>1))->order_by("id asc")->limit(2)->get()->result_array();
                foreach ($answer_replys_list as $key=>$reply){
                    $answer_replys_list[$key]['space_url1'] = web_url("u/".encrypt_user_id($reply['user_id']));
                    $answer_replys_list[$key]['space_url2'] = $reply['reply_id'] ? web_url("u/".encrypt_user_id($reply['reply_uid'])) : "";
                    $answer_replys_list[$key]['create_time'] = $this->set_time_two($reply['create_time']);
                    $answer_replys_list[$key]['answer_reply_id'] = encrypt_answer_reply_id($reply['id']);
                    $answer_replys_list[$key]['reply_url'] = web_url("wenda/".encrypt_wenda_id($reply['wenda_id'])."/answer/".  encrypt_answer_id($reply['answer_id'])."/reply-".encrypt_answer_reply_id($reply['id']));
                }
                $top_answer['reply'] = $answer_replys_list;
                $top_answer['reply_count'] = $top_answer['commentnum'];
                $top_answer['current_page'] = 0;
                $top_answer['is_self'] = 1;
                $top_answer['user_id'] = encrypt_user_id($top_answer['user_id']);
                $top_answer['is_answer_goto'] = 0;
                $top_answer['is_reply_goto'] = 0;
                $top_answer['is_page'] = 0;
                $top_answer['target_id'] = 0;
                $top_answer['share_url'] = share_url("wenda/".encrypt_wenda_id($top_answer['wenda_id'])."/answer-".  encrypt_answer_id($top_answer['id']));
                $top_answer['answer_url'] = web_url("wenda/".encrypt_wenda_id($top_answer['wenda_id'])."/answer-".  encrypt_answer_id($top_answer['id']));
                $top_answer['is_like'] = $this->bbs_userinfo['user_id'] ?($this->db->select("*")->from("bbs_wenda_answer_like")->where(array("user_id"=>$this->bbs_userinfo['user_id'],"answer_id"=>$top_answer['id'],"is_del"=>1))->order_by("id")->get()->num_rows() ? 1 : 0) : 0;
            } 
        }
        $this->assign("top_answer_id", $top_answer['id'] ? encrypt_answer_id($top_answer['id']) : "");
        
        //判断是否回答了该问题
        $wenda['is_answer'] = $this->bbs_userinfo['user_id'] ? ($this->db->select("*")->from("bbs_wenda_answer")->where(array("wenda_id"=>$wenda_id,"user_id"=>$this->bbs_userinfo['user_id'],"is_show"=>1))->order_by("id desc")->get()->num_rows() ? 1 : 0) : 0;
        
        //判断是否自己的问答
        $wenda['is_self'] = $this->bbs_userinfo['user_id'] == $wenda['questioner_id'];
        $wenda['detail_url'] = web_url("wenda/".encrypt_wenda_id($wenda_id));
        $wenda['space_url'] = web_url("u/".encrypt_user_id($wenda['questioner_id']));
        $wenda['create_time'] = date("Y-m-d H:i",$wenda['create_time']);
        
        $this->right();
        $this->related_qustion($wenda_id,$wenda['tags']);
        $this->assign("wenda", $wenda);
        $this->assign("top_answer", $top_answer);
        $this->assign('site_title', $wenda['title']);
        $this->display('wenda/detail.html');
    }
    //问答页面右侧数据
    private function right(){
        //总问题数
        $wenda_count = $this->db->select("*")->from("bbs_wenda")->where(array("is_show"=>1))->order_by("id desc")->get()->num_rows();
        //总回答数
        $answer_count = $this->db->select("*")->from("bbs_wenda_answer")->where(array("is_show"=>1))->order_by("id desc")->get()->num_rows();
        //热门标签
        $hot_tags = $this->db->select("id,name")->from("bbs_wenda_tags")->where(array("is_hot"=>1))->order_by("sort desc")->get()->result_array();
        foreach ($hot_tags as $key=>$val){
            $hot_tags[$key]['url'] = web_url("wenda/tag-".$val['id']);
        }
        //热门标签
        $common_tags = $this->db->select("id,name")->from("bbs_wenda_tags")->where("is_hot != 1")->order_by("sort desc")->get()->result_array();
        foreach ($common_tags as $key=>$val){
            $common_tags[$key]['url'] = web_url("wenda/tag-".$val['id']);
        }
        
        
        
        $this->assign("hot_tags", $hot_tags);
        $this->assign("common_tags", $common_tags);
        $this->assign("wenda_count", $wenda_count);
        $this->assign("answer_count", $answer_count);
    }
    
    //问答页面相关问题
    private function related_qustion($wenda_id,$tags){
        $like = "(";
        $count = count($tags);
        $index = 0;
        foreach ($tags as $key => $tag){
            $index += 1;
            if($count == $index){
                $like .= " (tags_name like '%$tag[tname]%')";
            }else{
                $like .= " (tags_name like '%$tag[tname]%') or ";
            }
            
        }
        $like .= ")";
        
        $relate_article = $this->db->query("select id,title,answernum from tan_bbs_wenda where id not in($wenda_id) and $like order by sort desc limit 5")->result_array();
        foreach ($relate_article as $key =>$val){
            $relate_article[$key]['wenda_url'] = web_url("wenda/".encrypt_wenda_id($val['id']));
        }
        $this->assign('relate_article', $relate_article);
    }
            
    
    function asking() {
        if(!$this->bbs_userinfo){//未登录状态
            web_redirect("site/login.html".$this->get_next_request_url());
        }
        $tag = $this->db->select("id,name")->from("bbs_wenda_tags")->where(array("is_recommend"=>1))->order_by("sort desc")->get()->result_array();
        $user_info = $this->db->select("email")->from("users")->where(array("user_id"=>$this->bbs_userinfo['user_id']))->get()->row_array();
        $user_email = $user_info['email'] ? email_formart($user_info['email']) : "";
        
        $this->asking_right_hot();
        
        $this->assign("user_email", $user_email);
        $this->assign("tags", $tag);
        $this->display('wenda/asking.html');
    }
    
    //问答提问界面右侧热门回答
    private function asking_right_hot(){
        $hot_wendas = $this->db->query("select id,title,answernum from tan_bbs_wenda where hot = 1 and is_show = 1 order by sort desc limit 5")->result_array();
        foreach ($hot_wendas as $key=>$val){
            $hot_wendas[$key]['wenda_url'] = web_url("wenda/".encrypt_wenda_id($val['id']));
        }
        $this->assign("hot_wendas", $hot_wendas);
    }
    
    //添加问答
    function add(){
        if($_POST){
            if(!$this->bbs_userinfo){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "您还未登录，请先登录哦";
                echo JSON($mess);exit;
            }
            
            $title = isset($_POST['wendaTitle']) ? trim($_POST['wendaTitle']) : "" ;//问答标题
            $content = isset($_POST['wendaContent']) ? trim($_POST['wendaContent']) : "" ;//问答内容
            $tags = isset($_POST['wendaTag']) ? trim($_POST['wendaTag']) : "" ;//问答标签
            $email_notice = isset($_POST['is_email']) ? trim($_POST['is_email']) : 0 ;//有回答是否邮件通知
            $title = strip_tags($title);
            if($title == ""){
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "问答标题不合法，请重新输入";
                echo JSON($mess);exit;
            }
            
            $allergicWord = file_get_contents("http://static.tan66.com/upfiles/files/badwords.txt");
            $allergicWord = str_replace(array("\r\n", "\r", "\n"),'',$allergicWord);
            $allergicWord= explode('|',$allergicWord);
            $info=0;
            $tinfo=0;
            for ($i=0;$i<count($allergicWord);$i++){  
                $check = substr_count($content, $allergicWord[$i]);
                $tcheck = substr_count($title,$allergicWord[$i]);
                if($check>0){
                    $info = $check;
                    break;
                }
                if($tcheck>0){
                    $tinfo = $tcheck;
                    break;;
                }
            }  
            if($info>0 || $tcheck>0){
                $errmes['reqStatus'] = false;
                $errmes['errorMsg'] = "检查您的问答标题或内容里面有非法或敏感内容，请修正";
                $errmes['errorCode'] = 1003;
                echo JSON($errmes);exit;
            }
            
            preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.bmp|\.jpeg]))[\'|\"].*?[\/]?>/i", $content, $matches);
            $thumb = $matches[1][0] ? $matches[1][0] : "";
            if($thumb){
                $result = $this->crypt->POST_Api("http://static.tan66.com/mimage/resize/150/100",array("file"=>$thumb));
                $result = json_decode($result,true);
                $thumb = $result['filename'];
            }else{
                $thumb = "";
            }
            $summary = mb_strcut(strip_tags(trim(str_replace("&nbsp;", "", $content))),0,300);
            $data = array();
            $data['questioner_id'] = $this->bbs_userinfo['user_id'];
            $data['title'] = $title;
            $data['content'] = strip_tags($content, "<br><img><p><div><a>");
            $data['summary'] = $summary;
            $data['thumb'] = $thumb;
            $data['tags_name'] = $tags;
            $data['create_time'] = time();
            $data['status'] = 1;
            $data['month'] = date("Ym");
            $data['day'] = date("Ymd");
            $data['is_email_noitce'] = $email_notice;
            $this->db->trans_begin();//开启事务
            
            $this->db->insert("bbs_wenda", $data);
            $insert_id = $this->db->insert_id();
            $query1 = $this->db->query("update tan_bbs_count set question_count = question_count + 1 where user_id = ".$this->bbs_userinfo['user_id']);
            //更新文章标签统计
            $tags ? $query2 = $this->update_tags($tags) : $query2 = 1;
            if($insert_id && $query1 && $query2){
                $this->db->trans_commit();//提交事务
                
                $this->db->insert("bbs_notice",array('user_id'=>$this->bbs_userinfo['user_id'],'operator_id'=>$insert_id,"event_type"=>'event_add_wenda',"type"=>"wenda","is_show"=>1,"create_time"=>time()));
                //发送消息
                $followers = $this->db->select("followuid")->from("bbs_fans")->where(array("user_id"=>$this->bbs_userinfo['user_id'],"is_del"=>1))->order_by("id desc")->get()->result_array();
                if($followers){
                    $datas = array();
                    foreach ($followers as $key=>$val){
                        $data = array();
                        $data['user_id'] = 0;
                        $data['recieve_id'] = $val['followuid'];
                        $data['operator_id'] = $insert_id;
                        $data['event_type'] = "event_add_wenda_care";
                        $data['create_time'] = time();
                        $data['is_show'] = 1;
                        $data['type'] = "wenda";
                        $datas[] = $data;
                    }
                    $datas[] = array('user_id'=>0,'recieve_id'=>$this->bbs_userinfo['user_id'],'operator_id'=>$insert_id,"event_type"=>'event_comment_wenda',"type"=>"wenda","is_show"=>1,"create_time"=>time());
                    $this->db->insert_batch("bbs_notice",$datas);
                }
                
                $mess['reqStatus'] = true;
                $mess['url'] = web_url("/wenda/".encrypt_wenda_id($insert_id));
                $mess['errorMsg'] = "发布成功，请耐心等待伙伴们的解答哦";
                echo JSON($mess);exit;
            }else{
                $this->db->trans_rollback();//事务回滚
                $mess['reqStatus'] = false;
                $mess['errorCode'] = 1000;
                $mess['errorMsg'] = "发布失败，请稍后重试";
                echo JSON($mess);exit;
            }
        }
        
    }
    
    
    
    //更新文章标签统计
    private function update_tags($tags){
        $flag = 1;
        $tag_arr = explode(",", $tags);
        foreach ($tag_arr as $key=>$val){
            $tag = explode("_", $val);
            
            $sql = "UPDATE tan_bbs_wenda_tags SET use_count = use_count + 1 WHERE id = $tag[1];";
            $flag = $this->db->query($sql);
            if(!$flag){
                break;
            }
        }
        
        return $flag;
        
    }
}
